/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode *sufficientSubset(TreeNode *root, int limit)
    {
        return dfs(root, limit, 0) < limit ? nullptr : root;
    }

    int dfs(TreeNode *tree, int limit, int accumulated)
    {
        if (tree->left == nullptr && tree->right == nullptr)
        {
            return tree->val;
        }

        accumulated += tree->val;

        int maxSubLeafPath = INT_MIN;
        if (tree->left != nullptr)
        {
            int leftSubMax = dfs(tree->left, limit, accumulated);
            if (accumulated + leftSubMax < limit)
            {
                tree->left = nullptr;
            }
            maxSubLeafPath = max(maxSubLeafPath, leftSubMax);
        }
        if (tree->right != nullptr)
        {
            int rightSubMax = dfs(tree->right, limit, accumulated);
            if (accumulated + rightSubMax < limit)
            {
                tree->right = nullptr;
            }
            maxSubLeafPath = max(maxSubLeafPath, rightSubMax);
        }

        return maxSubLeafPath + tree->val;
    }
};